package cn.b.sky.user.service.impl;

import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.dao.MenuTranslationDao;
import cn.b.sky.user.service.MenuTranslationService;
import cn.b.sky.user.service.model.Menu;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class MenuTranslationServiceImpl implements MenuTranslationService {

  @Autowired
  private MenuTranslationDao menuTranslationDao;

  private String getSiteCode() {
    return SecurityContextUtil.getSiteCode();
  }

  private void setCreateInfo(Menu menu) {
    menu.setSiteCode(getSiteCode());
    menu.setCreateUser(SecurityContextUtil.getCurrentUserName());
    menu.setCreateDateTime(new Date());
    menu.setModifyUser(SecurityContextUtil.getCurrentUserName());
    menu.setModifyDateTime(new Date());
  }

  @Override
  public List<Menu> getMenuListByCode(String menuCode, String sourceLanguage, String targetLanguage) {
    return menuTranslationDao.getTargetMenuListByCode(getSiteCode(), menuCode, sourceLanguage, targetLanguage);
  }

  @Override
  public void saveMenuList(List<Menu> menuList, String targetLanguage) {
    for (Menu menu : menuList) {
      setCreateInfo(menu);
      menu.setLanguageCode(targetLanguage);
      if (StringUtils.isEmpty(menu.getTargetMenuText())) {
        menuTranslationDao.deleteTargetMenu(menu);
      } else if (null == menuTranslationDao.selectTargetMenu(menu)) {
        menuTranslationDao.insertTargetMenu(menu);
      } else {
        menuTranslationDao.updateTargetMenu(menu);
      }
    }
  }

}
